package com.xywl.escort.view.pay.project

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.*
import com.xywl.escort.common.Constant
import com.xywl.escort.common.PreferenceKeys.USER_ID
import com.xywl.escort.utils.NumberFormatUtils
import com.xywl.escort.utils.RxSPTool
import com.xywl.escort.utils.ToastUtil
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_project_pay_dialog.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import java.math.BigDecimal
import javax.inject.Inject

/**
 * 项目支付弹窗界面
 */
@Route(path = "/xy/project/pay/dialog")
class ProjectPayDialogActivity : BaseActivity(), ProjectPayDialogContract.View {
    private val REQUEST_CODE_CHOOSE_COUPON = 26

    private var coupon: CouponBean? = null // 80 // 80 // 80
    private var bandBean: BandCardListResp.DataBean.ListBean? = null
    // 需要支付的价钱
    @Autowired
    @JvmField
    internal var payMoney = BigDecimal("0") // 980 // 200 // 980

    @Autowired
    @JvmField
    var condMinDay: Int = 0

    // 优惠券金额
    private var couponPayMoney = BigDecimal("0")

    // 用户账户余额
    private var accountFundsYuan = BigDecimal("0")

    // 使用账户支付金额
    private var accountPayMoney = BigDecimal("0") // 500 (500) // 500 (120) // 0 (0)

    // 使用银行卡支付
    private var thirdAccountPayPrice = BigDecimal("0") // 980 - 500 - 80 = 400 // 0 // 980 - 80 = 900

    @Autowired
    @JvmField
    var projectId: String = ""

    @Autowired
    @JvmField
    var numStr: String = "0"

    private var recordId = ""

    private var isCheckedAccountMoney = false

    @Inject
    lateinit var mPresenter: ProjectPayDialogContract.Presenter

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_project_pay_dialog)
        ARouter.getInstance().inject(this)

        initView()
        initData()
        addListener()
        EventBus.getDefault().register(this)
    }

    private fun initView() {
        Timber.e("payMoney=$payMoney")
        Timber.e("condMinDay=$condMinDay")
        thirdAccountPayPrice = payMoney
        val strPayMoney = "￥:" + NumberFormatUtils.getInstance().format(thirdAccountPayPrice.toDouble())
        text_pay_price.text = strPayMoney
    }

    private fun initData() {
        mPresenter.takeView(this)
        mPresenter.isPacket("1", condMinDay, payMoney.toDouble())
    }

    override fun onResume() {
        super.onResume()
        mPresenter.takeView(this)
        mPresenter.getBandCardList("DC", 1, 1)
        val userId = RxSPTool.getString(this, USER_ID)
        mPresenter.getUserFunds(userId)
    }

    private fun addListener() {
        text_coupon.setOnClickListener {
            ARouter.getInstance()
                    .build("/xy/coupon")
                    .withInt("condMinDay", condMinDay)
                    .withDouble("condMinPrice", payMoney.toDouble())
                    .withString("useScene", "1")
                    .withInt("type", 2)
                    .navigation(this, REQUEST_CODE_CHOOSE_COUPON)
        }

        image_close.setOnClickListener {
            finish()
        }

        sb_use_balance.setOnCheckedChangeListener { _, isChecked ->
            isCheckedAccountMoney = isChecked
            if (isChecked) {
                // 使用账户余额
                if (accountFundsYuan > payMoney) {
                    // 账户余额大于支付金额
                    accountPayMoney = payMoney.subtract(couponPayMoney)
                    thirdAccountPayPrice = BigDecimal("0")
                } else {
                    // 账户余额小于支付金额
                    accountPayMoney = accountFundsYuan.subtract(couponPayMoney)
                    thirdAccountPayPrice = payMoney.subtract(accountPayMoney).subtract(couponPayMoney)
                }
                val strPayMoney = "￥:" + NumberFormatUtils.getInstance().format(thirdAccountPayPrice.toDouble())
                text_pay_price.text = strPayMoney
            } else {
                // 不使用账户余额
                accountPayMoney = BigDecimal("0")
                thirdAccountPayPrice = payMoney.subtract(couponPayMoney)
                val strPayMoney = "￥:" + NumberFormatUtils.getInstance().format(thirdAccountPayPrice.toDouble())
                text_pay_price.text = strPayMoney
            }
        }

//        text_band_card.setOnClickListener {
//            ARouter.getInstance()
//                    .build("/xy/band/card/dialog")
//                    .withObject("bandBean", bandBean)
//                    .navigation(this, REQUEST_CODE_CHOOSE_BAND_CARD)
//        }

        text_add_band_card.setOnClickListener {
            val userId = RxSPTool.getString(this, USER_ID)
            mPresenter.isSetPayPwd(userId)
        }

        btn_confirm.setOnClickListener {
            val req = SubscribeBuyReq()
            req.projectId = projectId
            req.isChooseAgreement = 1
            req.num = numStr
            req.fundPayMoneyYuan = accountPayMoney
            req.thirdPartyPayMoneyYuan = thirdAccountPayPrice
            if (null != coupon) {
                req.redPacketReceiveId = coupon!!.id
            }
            if (null != bandBean) {
                req.userBankCardId = bandBean!!.id
            }
            // 认购第一步-下单
            mPresenter.subscribeBuy(req)
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun existPacketSuccess() {
        text_coupon.text = "有可用红包"
        text_coupon.setTextColor(ContextCompat.getColor(this, R.color.aid_prompt_color))
    }

    override fun unExistPacket() {
        text_coupon.text = "无可用红包"
        text_coupon.setTextColor(ContextCompat.getColor(this, R.color.main_body_normal_color))
    }

    override fun getUserFundsSuccess(dataBean: UserFundInfoResp.DataBean?) {
        if (!TextUtils.isEmpty(dataBean!!.accountFundsYuan)) {
            accountFundsYuan = BigDecimal(dataBean.accountFundsYuan)
        } else {
            accountFundsYuan = BigDecimal("0")
        }
        val accountBalance = "账户余额(" + NumberFormatUtils.getInstance().format(accountFundsYuan.toDouble()) + "元)"
        text_account_balance.text = accountBalance
    }

    override fun getUserFundsFailure() {
        accountFundsYuan = BigDecimal("0")
    }

    override fun getBandCardListSuccess(dataBean: BandCardListResp.DataBean?) {
        val list = dataBean!!.list
        if (list.size > 0) {
            bandBean = list[0]
            val item = list[0]
            var bankName = item.bankName
            val bankCardNo = item.bankCardNo
            if (bankCardNo.length > 4) {
                bankName += " (" + bankCardNo.substring(bankCardNo.length - 4, bankCardNo.length) + ")"
            } else {
                bankName += " ($bankCardNo)"
            }
            text_add_band_card.visibility = View.GONE
            text_band_card.visibility = View.VISIBLE
            text_band_card.text = bankName
        } else {
            text_add_band_card.visibility = View.VISIBLE
            text_band_card.visibility = View.GONE
        }
    }

    override fun getBandCardListFailure() {
        Timber.e("getBandCardListFailure")
        text_add_band_card.visibility = View.VISIBLE
        text_band_card.visibility = View.GONE
    }

    override fun subscribeBuyNoPayPwd(dataBean: SubscribeBuyResp.DataBean?) {
        // 认购第一步-下单成功 不需要输入支付密码
        // 直接调用认购第二步-支付申请接口
        recordId = dataBean!!.id
        mPresenter.payApply(recordId)
    }

    override fun subscribeBuyPayPwd(dataBean: SubscribeBuyResp.DataBean?) {
        // 认购第一步-下单成功 需要输入支付密码
        // 跳转到校验支付密码界面
        ARouter.getInstance().build("/xy/verify/pay/pwd")
                .withInt("type", 2)
                .withString("recordId", dataBean!!.id)
                .navigation()
    }

    override fun subscribeBuyFailure(msg: String?) {
        // 认购第一步-下单失败
        ToastUtil.showTip(this, msg)
    }

    override fun payApplySuccess(data: String?) {
        // 认购第二步-支付申请成功
        // data=1时，表示不使用银行卡支付，此时支付完成，不需要再调用【支付确认】接口； 当data=2时，表示需要使用银行卡支付，支付未完成，此时需要调用【支付确认】接口
        if (data.equals("1")) {
            ARouter.getInstance()
                    .build("/xy/order/subscribe/detail")
                    .withString("id", recordId)
                    .navigation()
        } else {
            // 调用确认支付界面
            ARouter.getInstance()
                    .build("/xy/pay/confirm")
                    .withString("id", recordId)
                    .navigation()
        }
    }

    override fun payApplyFailure(msg: String?) {
        // 认购第二步-支付申请失败
        ToastUtil.showTip(this, msg)
    }

    override fun hasSetPayPwd() {
        ARouter.getInstance().build("/xy/verify/pay/pwd")
                .withString("path", "/xy/band/card/bind")
                .navigation()
    }

    override fun noSetPayPwd() {
        ARouter.getInstance().build("/xy/pwd/setting/pay").navigation()
    }

    override fun findIsFitPayPwdFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun mainEventBus(event: MessageEvent) {
        Timber.tag("ProjectPayDialogActivity").e("event.message=" + event.message)
        Timber.tag("ProjectPayDialogActivity").e("event.type=" + event.type)
        when (event.type) {
            Constant.EventType.EVENT_PAY_SUCCESS -> {
                val message = event.message
                if (!TextUtils.isEmpty(message)) {
                    if (message == Constant.EventMessage.PAY_SUCCESS) {
                        finish()
                    } else if (message == Constant.EventMessage.PAY_BALANCE_SUCCESS) {
                        finish()
                    }
                }
            }
            else -> {
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_CHOOSE_COUPON -> {
                    data?.let {
                        coupon = data.getSerializableExtra("coupon") as CouponBean
                        Timber.tag("ProjectPayDialogActivity").e("coupon.name=${coupon!!.name}")
                        couponPayMoney = coupon!!.amountOfMoneyYuan
                        val money = "￥" + NumberFormatUtils.getInstance().format(couponPayMoney.toDouble())
                        text_coupon.text = money

                        // 选择使用账户余额
                        if (isCheckedAccountMoney) {
                            // 账户余额大于0
                            if (accountFundsYuan.toDouble() > 0) {
                                // 账户余额大于总价减去优惠券价格
                                if (accountFundsYuan > payMoney.subtract(couponPayMoney)) {
                                    accountPayMoney = payMoney.subtract(couponPayMoney)
                                    thirdAccountPayPrice = BigDecimal("0")
                                } else {
                                    // 账户余额小于总价减去优惠券价格 账户余额支付余额为所有当前账户资金
                                    accountPayMoney = accountFundsYuan
                                    thirdAccountPayPrice = payMoney.subtract(accountFundsYuan).subtract(couponPayMoney)
                                }
                            } else {
                                // 账户余额等于0
                                accountPayMoney = BigDecimal("0")
                                thirdAccountPayPrice = payMoney.subtract(couponPayMoney)
                            }
                        } else {
                            // 不使用账户余额
                            accountPayMoney = BigDecimal("0")
                            thirdAccountPayPrice = payMoney.subtract(couponPayMoney)
                        }

                        val strPayMoney = "￥:" + NumberFormatUtils.getInstance().format(thirdAccountPayPrice.toDouble())
                        text_pay_price.text = strPayMoney
                    }
                    Timber.tag("ProjectPayDialogActivity").e("data=$data")
                }
                else -> {
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}
